package com.chujiu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chujiu.dto.AccountPersonDto;
import com.chujiu.dto.MemberInfo;
import com.chujiu.dto.UserDto;
import com.chujiu.utils.HFJsonUtil;
import com.chujiu.utils.HttpsUtil;
import com.chujiu.utils.MapDetail;
import com.chujiu.utils.UtilDatetime;
import com.chujiu.utils.sign.SignVerifyHandle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 系统demo 的controller
 * Created by dell on 2018/5/31.
 * @author  王招
 */
@Controller
@Slf4j
public class SystemController {
    @Value("${chujiu-court.vip_num}")
    private String VIP_NUM;
    @Value("${chujiu-court.direct_way_url}")
    private String DIRECT_WAY_URL;
    @Value("${chujiu-court.gate_way_url}")
    private String GATE_WAY_URL;
    @Value("${chujiu-court.account_reback_url}")
    private String ACCOUNT_REBACK_Url;
    @Value("${chujiu-court.home_reback_url}")
    private String HOME_REBACK_Url;
    @Value("${chujiu-court.court_ip}")
    private String COURT_IP;
    @Value("${chujiu-court.local_ip}")
    private String LOCAL_IP;
    @Value("${chujiu-court.version_id}")
    private String VERSION_ID;
    @Autowired
    private  HttpsUtil httpUtil;
    @Autowired
    private SignVerifyHandle signVerifyHandle;

    @RequestMapping("/")
    public String login_method(){
        return "login";
    }

    /**
     * 登录
     * @param request
     * @param response
     * @param userDto
     * @return
     */
    @RequestMapping("/login_btn")
    public String loginBtn_method(HttpServletRequest request, HttpServletResponse response,UserDto userDto){
        userDto.setId(75L);
        userDto.setGender("0");
        userDto.setPhone(userDto.getName());

            if(userDto!=null){
                MapDetail.resMap.put("platfmCustId",userDto.getId());
            }
            log.info("进入home页面,发送token请求");
            //自己做了一个缓存，存储一些必要信息
            MapDetail.resMap.put("source",userDto.getSource());
            //获取token  直连接口
            Map<String,Object> map=new HashMap<>();
            map.put("platfmCustId",userDto.getId());
            map.put("source",userDto.getSource());
            String token = sendToken(map,COURT_IP+DIRECT_WAY_URL);
            if(token==null && token.equals("")){
               return "error";
            }
            MapDetail.resMap.put("token",token);
            MapDetail.resMap.put("userName",userDto.getName());
            MapDetail.resMap.put("phone",userDto.getPhone());
        return "home";
    }

    /**
     * 开户界面
     * @return
     */
    @RequestMapping("/personAccount")
    public String personAccount_method(){
        return "personAccount";
    }

    /**
     * 个人开户
     * @param request
     * @param role
     * @return
     */
    @RequestMapping("/personAccount_btn")
    public ModelAndView personAccountBtn_method(HttpServletRequest request, String role){
        AccountPersonDto accountPersonDto=new AccountPersonDto();
        accountPersonDto.setRole(role);
        accountPersonDto.setPlatfmCustId(MapDetail.resMap.get("platfmCustId").toString());
        SignVerifyHandle signVerifyHandle=new SignVerifyHandle();
        String s = signVerifyHandle.signData(VIP_NUM, JSON.toJSONString(accountPersonDto));

        SimpleDateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");
        JSONObject jsonhead = new JSONObject(true);
        JSONObject jsonbody = new JSONObject(true);

        // head
        jsonhead.put("serviceName","PERSON_REGISTER");//接口名称
        jsonhead.put("vipNum",VIP_NUM);//会员编号（平台编号）
        jsonhead.put("requestDt", UtilDatetime.getDateString());//请求时间
        jsonhead.put("requestTm", UtilDatetime.getTimeString5());//请求时间
        jsonhead.put("requestNo", "011"+df.format(new Date()));//请求流水(贯穿整个请求返回)
        jsonhead.put("signData",s);
        jsonhead.put("source",MapDetail.resMap.get("source").toString());//source
        jsonhead.put("token",MapDetail.resMap.get("token").toString());
        jsonhead.put("version",VERSION_ID);//版本号
        jsonhead.put("rebackUrl",HOME_REBACK_Url+ACCOUNT_REBACK_Url);//业务处理结果返回url

        Map<String,Object> resMap=new HashMap<>();
        resMap.put("head",JSON.toJSONString(jsonhead));
        resMap.put("body",JSON.toJSONString(accountPersonDto));
        resMap.put("urlString",COURT_IP+GATE_WAY_URL);

        ModelAndView model=new ModelAndView();
        model.setViewName("gateWayPost");
        model.addObject("resMap",resMap);

        return model;
    }

    /**
     * 查询用户信息
     * @param request
     * @return
     */
    @RequestMapping("/queryUserInfo")
    public ModelAndView queryUserInfo_method(HttpServletRequest request){
        Map<String,Object> map=new HashMap<>();
        map.put("token",MapDetail.resMap.get("token").toString());
        map.put("platfmCustId",MapDetail.resMap.get("platfmCustId").toString());
        map.put("source",MapDetail.resMap.get("source").toString());
        map.put("role",MapDetail.resMap.get("role"));

        List<MemberInfo> memberInfoList=sendUserList(map, COURT_IP+DIRECT_WAY_URL);

        ModelAndView model=new ModelAndView();
        model.setViewName("userInfo");
        model.addObject("list",memberInfoList);

        return model;
    }

    /**
     * 充值
     * @param request
     * @param role
     * @return
     */
    @RequestMapping("/recharge")
    public ModelAndView recharge_method(HttpServletRequest request, String role){
        JSONObject jsonhead = new JSONObject(true);
        JSONObject jsonbody = new JSONObject(true);
        jsonbody.put("platfmCustId",MapDetail.resMap.get("platfmCustId").toString());
        jsonbody.put("role",MapDetail.resMap.get("role").toString());

        SignVerifyHandle signVerifyHandle=new SignVerifyHandle();
        String s = signVerifyHandle.signData(VIP_NUM, jsonbody.toJSONString());

        // head
        jsonhead.put("serviceName","MEMBER_RECHARG");//接口名称
        jsonhead.put("vipNum",VIP_NUM);//会员编号（平台编号）
        jsonhead.put("requestDt", UtilDatetime.getDateString());//请求时间
        jsonhead.put("requestTm", UtilDatetime.getTimeString5());//请求时间
        jsonhead.put("requestNo", "110"+UtilDatetime.getTimeString5());//请求流水(贯穿整个请求返回)
        jsonhead.put("signData",s);
        jsonhead.put("source",MapDetail.resMap.get("source").toString());//source
        jsonhead.put("token",MapDetail.resMap.get("token").toString());
        jsonhead.put("version",VERSION_ID);//版本号
        jsonhead.put("rebackUrl",LOCAL_IP+HOME_REBACK_Url);//业务处理结果返回url

        Map<String,Object> resMap=new HashMap<>();
        resMap.put("head",JSON.toJSONString(jsonhead));
        resMap.put("body",JSON.toJSONString(jsonbody));
        resMap.put("urlString",COURT_IP+GATE_WAY_URL);

        ModelAndView model=new ModelAndView();
        model.setViewName("gateWayPost");
        model.addObject("resMap",resMap);

        return model;
    }

    /**
     * 个人和企业开会网关返回报文
     * @param request
     */
    @RequestMapping("/accountReBack")
    public ModelAndView accountReBack_method(HttpServletRequest request){
        String head = request.getParameter("head");
        String body=request.getParameter("body");
        log.info("开户网关通知返回报文信息："+head +body);
        ModelAndView modelAndView=new ModelAndView();
        try {
            Map<String, String> headMap = HFJsonUtil.getJsonToMap(head);
            Map<String,String> mapRes=new HashMap<>();
            if("000000".equals(headMap.get("code"))){
                if(signVerifyHandle.verifySign(VIP_NUM,body, headMap.get("signData"))){
                    mapRes= HFJsonUtil.getJsonToMap(body);
                    //如果成功跳转到开户成功页面
                    modelAndView.setViewName("accountnotice");
                    modelAndView.addObject("mapRes",mapRes);

                }else{
                    log.info("用户信息查询返回信息:验签失败");
                }
            }else if("100008".equals(headMap.get("code"))){
                mapRes.put("error","用户信息不存在");
            }else if("100001".equals(headMap.get("code"))){
                mapRes.put("error","签名验证失败");
            }else if("100002".equals(headMap.get("code"))){
                mapRes.put("error","TOKEN验证失败");
            }else if("100003".equals(headMap.get("code"))){
                mapRes.put("error","TOKEN失效");
            }else if("100004".equals(headMap.get("code"))){
                mapRes.put("error","平台编号不存在");
            }else if("100005".equals(headMap.get("code"))){
                mapRes.put("error","平台状态异常");
            }else if("100006".equals(headMap.get("code"))){
                mapRes.put("error","请求流水号重复");
            }else if("100007".equals(headMap.get("code"))){
                mapRes.put("error","参数必输项校验未通过");
            }else if("100010".equals(headMap.get("code"))){
                mapRes.put("error","该用户已存在,请勿重复注册!");
            }else if("100011".equals(headMap.get("code"))){
                mapRes.put("error","暂无产品信息");
            }

        }catch (Exception e){
            e.printStackTrace();
            log.info("对不起，报错啦！！接收的数据"+head+body);
        }
        return  modelAndView;
    }

    /**
     * jms异步通知返回报文
     * @param request
     * @param response
     */
    @RequestMapping("/asyncNotice")
    public void asyncNotice_method(HttpServletRequest request,HttpServletResponse response){
        String requestJson=null;
        try {

        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }
        requestJson =sb.toString();
        log.info("异步通知返回报文信息："+requestJson);

            Map<String, String> jsonToMap = HFJsonUtil.getJsonToMap(requestJson);
            Map<String, String> headMap = HFJsonUtil.getJsonToMap(jsonToMap.get("head"));
            Map<String,String> mapRes=new HashMap<>();
            if("000000".equals(headMap.get("code"))){
                if(signVerifyHandle.verifySign(VIP_NUM,jsonToMap.get("body"), headMap.get("signData"))){
                    mapRes= HFJsonUtil.getJsonToMap(jsonToMap.get("body"));

                    log.info("异步通知返回报文body"+mapRes);
                }else{
                    log.info("异步通知返回报文:验签失败");
                }
            }else if("100008".equals(headMap.get("code"))){
                mapRes.put("error","用户信息不存在");
            }else if("100001".equals(headMap.get("code"))){
                mapRes.put("error","签名验证失败");
            }else if("100002".equals(headMap.get("code"))){
                mapRes.put("error","TOKEN验证失败");
            }else if("100003".equals(headMap.get("code"))){
                mapRes.put("error","TOKEN失效");
            }else if("100004".equals(headMap.get("code"))){
                mapRes.put("error","平台编号不存在");
            }else if("100005".equals(headMap.get("code"))){
                mapRes.put("error","平台状态异常");
            }else if("100006".equals(headMap.get("code"))){
                mapRes.put("error","请求流水号重复");
            }else if("100007".equals(headMap.get("code"))){
                mapRes.put("error","参数必输项校验未通过");
            }else if("100010".equals(headMap.get("code"))){
                mapRes.put("error","该用户已存在,请勿重复注册!");
            }else if("100011".equals(headMap.get("code"))){
                mapRes.put("error","暂无产品信息");
            }

        }catch (Exception e){
            e.printStackTrace();
            log.info("对不起，报错啦！！接收的数据"+requestJson);
        }
    }



    /**
     * 获取Token 发送报文
     * @param map
     * @param urlString
     * @return
     */
    public String  sendToken(Map<String,Object> map,String urlString){
        SimpleDateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");
        JSONObject jsonData = new JSONObject(true);
        JSONObject jsonhead = new JSONObject(true);
        JSONObject jsonbody = new JSONObject(true);

        // head
        jsonhead.put("serviceName","GET_TOKEN");//接口名称
        jsonhead.put("vipNum", VIP_NUM);//会员编号（平台编号）
        jsonhead.put("requestDt", UtilDatetime.getDateString());//请求时间
        jsonhead.put("requestTm", UtilDatetime.getTimeString5());//请求时间
        jsonhead.put("requestNo", "110"+df.format(new Date()));//请求流水(贯穿整个请求返回)
        jsonhead.put("source",map.get("source"));//source
        jsonhead.put("version",VERSION_ID);//版本号
        // body
        jsonbody.put("platfmCustId", map.get("platfmCustId"));//用户所在平台ID

        jsonData.put("head", jsonhead);
        jsonData.put("body", jsonbody);
        JSONObject newjson = new JSONObject();
        String b = null;
        try {
            b = signVerifyHandle.signData(VIP_NUM, jsonData.getString("body"));
            jsonData.getJSONObject("head").put("signData", b);
        } catch (Exception e) {
            e.printStackTrace();
        }
        newjson.put("head", jsonData.getJSONObject("head"));
        newjson.put("body", jsonData.getJSONObject("body"));
        log.info("请求token发送报文:"+newjson.toString());
        Map<String,String> mapRes=new HashMap<>();
        String res =null;
        try {
            res =HttpsUtil.doPost(urlString,newjson.toString());
            log.info("返回报文内容:"+"||"+res);
            mapRes= HFJsonUtil.getJsonToMap(res);
            res=httpUtil.getResultMap(mapRes);

            log.info("返回token:"+"||"+res);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  res;
    }

    /**
     * 获取用户信息 发送报文
     * @param  map
     * @param  urlString
     * @return
     */
    public List<MemberInfo> sendUserList(Map<String,Object> map, String urlString){
        SimpleDateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");
        JSONObject jsonData = new JSONObject(true);
        JSONObject jsonhead = new JSONObject(true);
        JSONObject jsonbody = new JSONObject(true);

        // head
        jsonhead.put("serviceName","QUERY_CUST_INFO");
        jsonhead.put("vipNum",VIP_NUM);//会员编号（平台编号）
        jsonhead.put("requestDt", UtilDatetime.getDateString());//请求时间
        jsonhead.put("requestTm", UtilDatetime.getTimeString5());//请求时间
        jsonhead.put("requestNo", "114"+df.format(new Date()));//请求流水(贯穿整个请求返回)
        jsonhead.put("token",map.get("token"));//token
        jsonhead.put("source",map.get("source"));//sessionId
        jsonhead.put("version",VERSION_ID);//版本号
        // body
        jsonbody.put("platfmCustId", map.get("platfmCustId"));//所在平台该用户ID（用户在普惠家的ID）
        jsonbody.put("role", map.get("role"));//角色

        jsonData.put("head", jsonhead);
        jsonData.put("body", jsonbody);
        JSONObject newjson = new JSONObject();
        String b = null;
        try {
            b = signVerifyHandle.signData(VIP_NUM, jsonData.getString("body"));
            jsonData.getJSONObject("head").put("signData", b);
        } catch (Exception e) {
            e.printStackTrace();
        }
        newjson.put("head", jsonData.getJSONObject("head"));
        newjson.put("body", jsonData.getJSONObject("body"));
        log.info("获取用户信息发送报文:"+newjson.toString());
        Map<String,String> mapRes=new HashMap<>();
        List<MemberInfo> memberInfoList=new ArrayList<>();
        String res =null;
        try {
            res =HttpsUtil.doPost(urlString,newjson.toString());
            log.info("获取用户信息返回报文:"+res);
            // net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(res);
            Map<String, String> jsonToMap = HFJsonUtil.getJsonToMap(res);
            Map<String, String> headMap = HFJsonUtil.getJsonToMap(jsonToMap.get("head"));
            if("000000".equals(headMap.get("code"))){
                if(signVerifyHandle.verifySign(VIP_NUM,jsonToMap.get("body"), headMap.get("signData"))){
                    memberInfoList = JSONObject.parseArray(HFJsonUtil.getJsonToMap(jsonToMap.get("body")).get("custInfoList"), MemberInfo.class);
                    MapDetail.resMap.put("role",memberInfoList.get(0).getRole());
                }else{
                    log.info("用户信息查询返回信息:验签失败");
                }
            }else{
                log.info("用户信息查询返回信息message:"+"||"+jsonToMap.get("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  memberInfoList;
    }



}
